<template>
  <view class="app bg-white" v-if="showView">
    <!-- 轮播图 -->
    <mt-carousel
      :list="carousels"
      :height="praise.carousel_height"
      :autoplay="false"
      :preview="true"
      v-if="carousels.length > 0"
    ></mt-carousel>

    <view class="img-zone" v-else>
      <image class="poster" mode="widthFix" :src="praise.poster"></image>
    </view>

    <!-- 关联商品 -->
    <view class="relate-box" v-if="praise.relate_id > 0" @click="gotoGoods(praise.relate_id)">
      <view class="flex">
        <image :src="praise.relate_info.goods_logo"></image>
      </view>
      <view class="relate-area">
        <text class="relate-title line-1">{{ praise.relate_info.goods_name }}</text>
        <view class="price">￥{{ praise.relate_info.goods_specs[0].goods_price }}</view>
      </view>
    </view>

    <!-- 口碑标题 -->
    <view class="title-box">
      <text class="title">{{ praise.title }}</text>
    </view>

    <!-- 口碑详情 -->
    <view class="content">
      <mt-uparse :html="praise.content" :preview="false" :selectable="true"></mt-uparse>
    </view>

    <!-- 分享 -->
    <view class="share-box">
      <view class="my-50rpx mr-30rpx">
        <button class="share-btn" open-type="share" hover-class="none">
          <image class="share-icon" src="@/static/icon/svg/video/share.svg" />
          <text>分享</text>
        </button>
      </view>
    </view>

    <!-- 评论 -->
    <mt-drawer v-model:show="showWin" height="70">
      <view class="drawer-box">
        <text class="comment-title">评论 ( {{ comments.total }} )</text>
        <view class="h-full">
          <view class="comment-box">
            <z-paging
              ref="paging"
              class="comment-list"
              v-model="comments.list"
              :default-page-size="comments.limit"
              :auto="false"
              :fixed="false"
              :min-delay="800"
              :show-loading-more-no-more-view="false"
              :auto-hide-loading-after-first-loaded="true"
              :refresher-enabled="false"
              @query="queryCommentData"
            >
              <view class="comment-item" v-for="(comment, index) in comments.list" :key="index">
                <view class="comment-left">
                  <image
                    class="user-avatar"
                    :src="comment.fansinfo.avatar || config.custom.avatar"
                    @error="comment.fansinfo.avatar = config.custom.avatar"
                  />
                </view>
                <view class="comment-right">
                  <text class="user-name">{{ comment.fansinfo.nickname }}</text>
                  <text class="comment-content">{{ comment.content }}</text>
                  <text class="comment-date">{{ getDayAgo(comment.created_at) }}</text>
                </view>
              </view>

              <template #empty>
                <view class="no-data-box">
                  <text>暂无评论</text>
                  <image class="no-data-img" src="@/static/image/video/chats.svg"></image>
                </view>
              </template>

              <template #loading>
                <view class="loading">
                  <mt-logo-loading :size="88"></mt-logo-loading>
                </view>
              </template>
            </z-paging>
          </view>
        </view>
      </view>
    </mt-drawer>
    <view class="dialog-box">
      <view class="dialog-text">
        <textarea
          class="dialog-textarea"
          type="textarea"
          placeholder="请友善发言"
          v-model="comment"
          :show-confirm-bar="false"
          :auto-height="true"
          :adjust-position="false"
          @focus="dialogFocus"
          @blur="dialogBlur"
        />
        <text class="send-btn" @click="sendComment()">发送</text>
        <view class="action-box">
          <view class="action-item" @click="openComment(!showWin)">
            <image class="acion-item-icon" src="@/static/icon/svg/video/msg_line.svg"></image>
            <text class="action-item-text">{{ praise.comment_num }}</text>
          </view>
          <view class="action-item" @click="setLike()">
            <image
              class="acion-item-icon"
              v-show="praise.is_like == 0"
              src="@/static/icon/svg/video/love_line.svg"
            ></image>
            <image
              class="acion-item-icon"
              v-show="praise.is_like == 1"
              src="@/static/icon/svg/video/love_active.svg"
            ></image>
            <text class="action-item-text">{{ praise.like_num }}</text>
          </view>
        </view>
      </view>
      <view class="keybord"></view>
    </view>
  </view>
</template>

<script lang="ts" setup>
  import mtCarousel from '@/components/mt-carousel/mt-carousel.vue';
  import mtUparse from '@/components/mt-uparse/mt-uparse.vue';
  import mtDrawer from '@/components/mt-drawer/mt-drawer.vue';
  import mtLogoLoading from '@/components/mt-loading/mt-logo-loading.vue';
  import { ref, reactive } from 'vue';
  import { onLoad, onShareAppMessage, onUnload } from '@dcloudio/uni-app';
  import {
    getPraiseDetail as getDataApi,
    setPraiseLike,
    getPraiseComments,
    setPraiseComment,
  } from '@/api/praise';
  import { report } from '@/utils/exception';
  import { getDayAgo, getNow } from '@/utils/day';
  import { msg } from '@/utils/msg';
  import { useFansStore } from '@/store/fans';
  import { config } from '@/config/env';
  import type { PraiseItem, PraiseCommentItem } from '@/types/praise';

  const fansStore = useFansStore();
  const showView = ref<boolean>(false);
  const carousels = ref<string[]>([]);
  const praise = ref<any>();

  let id = 0;
  let idx = -1;
  onLoad((option: any) => {
    id = option.id;
    if (option.idx) {
      idx = option.idx;
    }
    getDataApi(id)
      .then((res) => {
        praise.value = res.data as PraiseItem;
        console.log(praise.value);

        if (praise.value.image_url) {
          carousels.value = praise.value.image_url.split(',');
        }
        if (praise.value.video_url) {
          carousels.value.unshift(praise.value.video_url);
        }
        showView.value = true;
      })
      .catch((err) => {
        report(err);
      });
  });

  onUnload(() => {
    if (idx == -1) return false;
    uni.$emit('syncPraiseLike', {
      index: idx,
      is_like: praise.value.is_like,
      like_num: praise.value.like_num,
    });
  });

  // 点赞
  let timer: any;
  const setLike = () => {
    praise.value.is_like = praise.value.is_like == 0 ? 1 : 0;
    praise.value.is_like == 1
      ? praise.value.like_num++
      : praise.value.like_num > 0
        ? praise.value.like_num--
        : 0;

    clearTimeout(timer);
    timer = setTimeout(() => {
      setPraiseLike(praise.value.id, praise.value.is_like)
        .then((res) => {})
        .catch((err) => {
          report(err);
          praise.value.is_like = praise.value.is_like == 0 ? 1 : 0;
          praise.value.is_like == 1
            ? praise.value.like_num++
            : praise.value.like_num > 0
              ? praise.value.like_num--
              : 0;
        });
    }, 500);
  };

  const paging = ref();
  const showWin = ref<boolean>(false);
  const comment = ref<string>('');
  const comments = reactive({
    list: <PraiseCommentItem[]>[],
    limit: 6,
    total: 0,
  });

  const dialogBottom = ref<string>('0');
  const dialogFocus = (event: any) => {
    dialogBottom.value = event.detail.height > 0 ? event.detail.height + 'px' : '301px';
    openComment(true);
  };
  const dialogBlur = () => {
    dialogBottom.value = '0';
  };

  // 请求评论数据
  const queryCommentData = (pageNo: number, pageSize: number) => {
    getPraiseComments(pageNo, pageSize, praise.value.id)
      .then((res) => {
        comments.total = res.data.pages.total;
        praise.value.comment_num = comments.total;
        console.log(res.data.list);

        paging.value.complete(res.data.list);
      })
      .catch((err) => {
        report(err);
        paging.value.complete(false);
      });
  };

  // 打开评论
  let initComment = false;
  const openComment = (state: boolean) => {
    showWin.value = state;
    if (!initComment) {
      initComment = true;
      paging.value.reload();
    }
  };

  // 评论
  let commentTmp = '';
  const sendComment = () => {
    if (!comment.value) {
      return msg.error('请填写评论');
    }

    if (comment.value == commentTmp) {
      return msg.error('请勿重复评论');
    }

    msg.loading('发送中');
    setPraiseComment(praise.value.id, comment.value)
      .then((res) => {
        paging.value.addDataFromTop({
          fansinfo: { nickname: fansStore.fansinfo.nickname, avatar: fansStore.fansinfo.avatar },
          content: comment.value,
          created_at: getNow(),
        });
        commentTmp = comment.value;
        comment.value = '';
        comments.total++;
        praise.value.comment_num = comments.total;
        setTimeout(() => {
          msg.success('评论发送成功！');
        }, 500);
      })
      .catch((err) => {
        report(err);
      });
  };

  /* #ifdef MP-WEIXIN */
  // 分享
  onShareAppMessage((res) => {
    return {
      title: praise.value.title,
      path: '/pages/praise/detail?id=' + praise.value.id,
      imageUrl: praise.value.poster,
    };
  });

  uni.showShareMenu({
    menus: ['shareAppMessage', 'shareTimeline'],
    withShareTicket: true,
  });
  /* #endif */

  const gotoGoods = (goodsId: number) => {
    uni.navigateTo({ url: `/pages/goods/detail?id=${goodsId}` });
  };
</script>

<style lang="scss" scoped>
  .app {
    padding-bottom: 220rpx;
  }

  .title-box {
    display: flex;
    padding: 25rpx 25rpx 15rpx;

    .title {
      display: flex;
      padding-left: 5rpx;
      font-size: 30rpx;
      font-weight: 600;
      line-height: 45rpx;
    }
  }

  .content {
    letter-spacing: 1rpx;
    font-size: 28rpx;
  }

  .poster {
    width: 100%;
  }

  .relate-box {
    display: flex;
    margin: 25rpx 26rpx 0;
    padding: 15rpx;
    border-radius: 10rpx;
    box-shadow: rgba(99, 99, 99, 0.2) 0px 2px 8px 0px;

    image {
      width: 80rpx;
      height: 80rpx;
      border-radius: 10rpx;
      margin-right: 15rpx;
    }

    .relate-area {
      display: flex;
      flex-direction: column;
      justify-content: center;

      .relate-title {
        font-size: 26rpx;
        margin-bottom: 3rpx;
      }
      .price {
        color: $themeColor;
        font-size: 28rpx;
        font-weight: 600;
      }
    }
  }

  .share-box {
    display: flex;
    justify-content: flex-end;

    .share-btn {
      display: flex;
      height: 50rpx;
      padding: 0 20rpx;
      font-size: 24rpx;
      letter-spacing: 5rpx;
      align-items: center;
      justify-content: center;
      border-radius: 50rpx;
      color: white;
      background: #ff9d00;
      &::after {
        border: none;
      }
    }
    .share-icon {
      width: 35rpx;
      height: 35rpx;
      margin-right: 7rpx;
    }
  }

  .drawer-box {
    padding-bottom: 208rpx;
    height: 100%;

    .comment-title {
      display: flex;
      justify-content: center;
      font-size: 32rpx;
      font-weight: bold;
      padding: 25rpx 0;
    }

    .comment-box {
      height: 100%;

      .no-data-box {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        height: 700rpx;

        .no-data-img {
          width: 380rpx;
        }
      }

      .comment-list {
        height: 100%;

        .comment-item {
          display: flex;
          padding-top: 30rpx;
          padding-left: 40rpx;

          .comment-left {
            padding-right: 20rpx;

            .user-avatar {
              width: 80rpx;
              height: 80rpx;
              border-radius: 50%;
            }
          }

          .comment-right {
            display: flex;
            flex-direction: column;
            flex: 1;
            padding-right: 40rpx;
            padding-bottom: 30rpx;

            .user-name {
              font-size: 26rpx;
              color: #7e7e7e;
            }

            .comment-content {
              font-size: 29rpx;
              line-height: 40rpx;
              font-weight: 600;
              padding: 10rpx 0;
              letter-spacing: 2rpx;
            }

            .comment-date {
              font-size: 24rpx;
              color: #b5b5b5;
            }
          }

          &:not(:last-child) .comment-right {
            border-bottom: 1px solid #ececec;
          }
        }
      }
    }

    .loading {
      display: flex;
      align-items: center;
      justify-content: center;
      height: 500rpx;
    }
  }

  .dialog-box {
    position: fixed;
    left: 0;
    bottom: 0;
    width: 100%;
    background: white;
    box-shadow: rgba(0, 0, 0, 0.2) 0px 4px 12px;
    padding: 25rpx 20rpx 25rpx 35rpx;
    z-index: 30;
    // transition: all .2s ease;

    .dialog-text {
      display: flex;
      align-items: flex-end;

      .dialog-textarea {
        width: 400rpx;
        max-height: 240rpx;
        font-size: 30rpx;
        padding: 18rpx 20rpx;
        overflow-y: auto;
        border-radius: 12rpx;
        background: #f2f2f2;
      }

      .send-btn {
        display: flex;
        flex: none;
        font-size: 30rpx;
        background: $themeColor;
        color: white;
        padding: 19rpx 28rpx;
        margin-left: 20rpx;
        margin-right: 22rpx;
        border-radius: 12rpx;
      }

      .action-box {
        display: flex;
        justify-content: space-around;
        align-content: center;
        width: 140rpx;
        // background: lightgreen;

        .action-item {
          display: flex;
          flex-direction: column;
          align-items: center;
          .acion-item-icon {
            width: 40rpx;
            height: 40rpx;
          }
          .action-item-text {
            font-size: 24rpx;
            padding-top: 2rpx;
          }
        }
      }
    }

    .keybord {
      height: v-bind(dialogBottom);
    }
  }
</style>
